package com.mactivity.activities;

import java.util.ArrayList;
import java.util.Map;
import java.util.StringTokenizer;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import com.mactivity.helper.Constants;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.StrictMode;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;

import com.mactivity.database.AddFriendActivityFunctions;
import com.mactivity.helper.SharedPreferenceHelper;


/*
 * 
 * This class handles all the details regarding adding a friend
 * 
 * 
 */
public class AddFriendActivity extends Activity implements OnClickListener
{
	//Declarations
	SharedPreferenceHelper preferenceHelper;
	EditText frEmail;
	Button submit,search;
	private int addingYourself=0,alreadyFriends=0,notificationResult=0;
	private Integer I;
	private String myId,userId,myName,myEmailAdd,friendEmail,clickedEmail,user,receivedData;
	private ArrayList<String>emailValues= new ArrayList<String>();
	private ArrayList<String>nameEmailValues= new ArrayList<String>();
	private ArrayList<String>nameValues= new ArrayList<String>();
	private RadioGroup radioGroup;
	private RadioButton radioClicked;
	ArrayAdapter<String> adapter;
	StringTokenizer st2;
	ListView emailList;
	boolean check=false,friends=false,notification=false;
	AddFriendActivityFunctions  addFriendActivityFunction;
    @Override
    public void onCreate(Bundle savedInstanceState)
    {
    	StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()
    	.detectDiskReads().detectDiskWrites().detectNetwork() // or	.detectAll() for all detectable problems
		.penaltyLog().build());
    	super.onCreate(savedInstanceState);
        setContentView(R.layout.add_friend);
        
        //SharedPreferenceHelper class which helps retrieve logged in user's information
        preferenceHelper =  new SharedPreferenceHelper(this);
        Map<String, String> userInfo=preferenceHelper.getUserInformation();
 		I=new Integer(Integer.parseInt(userInfo.get(Constants.USER_ID)));
 		addFriendActivityFunction= new AddFriendActivityFunctions();
 		
 		//Retrieves Current User's Email Id
 		myEmailAdd=userInfo.get(Constants.USER_EMAIL_ID);
 		
 		//Retrieves Current User's Name
 		myName=userInfo.get(Constants.USER_NAME);
 		System.out.println("my:"+myEmailAdd+":"+myName);
 		//fetching entered email id
 		frEmail = (EditText) findViewById(R.id.emailId);
 		search = (Button) findViewById(R.id.searchfriend);
 		radioGroup= (RadioGroup) findViewById(R.id.radioOption);
        myId=I+"";   
        search.setOnClickListener(this);
        
    }
    public void onClick(View v)
    {
    	if(v.getId()==R.id.searchfriend)
    	{
    		int selectedId = radioGroup.getCheckedRadioButtonId();
    		 
			// find the radiobutton by returned id
    		radioClicked = (RadioButton) findViewById(selectedId);
 
			nameValues.clear();
    		nameEmailValues.clear();
    		emailValues.clear();
    		String checkUser;
    		friendEmail=frEmail.getText().toString()+"%";
    		// this function call is to check if the user is valid user
    		if(radioClicked.getText().equals("Email"))
    		checkUser=addFriendActivityFunction.findUser(friendEmail);
    		else
    			checkUser=addFriendActivityFunction.findUserByName(friendEmail);
    		//checkUser= checkUser.replaceAll("\\s+", "");
    		try
    		{
    			if(checkUser.equals("null"))
    			{
    				Toast.makeText(this, "Invalid user "+ frEmail.getText().toString(),
    						Toast.LENGTH_LONG).show();
    			}
    			else
    			{
    				receivedData = "";
    				JSONArray jArray = new JSONArray(checkUser);
    				JSONObject json_data;
    				for(int i=0;i<jArray.length();i++)
    				{
    					json_data = jArray.getJSONObject(i);
    					if(radioClicked.getText().equals("Email"))
    					emailValues.add(json_data.getString(Constants.JSON_STRING_EMAIL));
    					else{
    						nameEmailValues.add(json_data.getString(Constants.JSON_STRING_NAME)+" ("+json_data.getString(Constants.JSON_STRING_EMAIL));
    						nameValues.add(json_data.getString(Constants.JSON_STRING_NAME));
    					}
    					check=true;
    					receivedData += "\n" + json_data.getString(Constants.JSON_STRING_NAME)+json_data.getString(Constants.JSON_STRING_EMAIL);
    					System.out.println(receivedData);
    				}
    			}
    			if(radioClicked.getText().equals("Email"))emailFunction();
    			else nameFunction();
    			   		}
    		catch(Exception ee)
    		{
    			ee.printStackTrace();
    		}
    	}//switch ends
}//onclick ends
    
    
    private void nameFunction() {
    	adapter=new ArrayAdapter<String>(this,
				android.R.layout.simple_list_item_1,
				nameValues);
		emailList = (ListView) findViewById(R.id.userList);
		emailList.setAdapter(adapter);
		emailList.setTextFilterEnabled(true);
		emailList.setOnItemClickListener(new OnItemClickListener(){
			
			@Override
			/*
			 * This method fetches the information about the clicked item in the listview 
			 * and asks if user wants to add as a friend 
			 * 
			 */
			public void onItemClick(AdapterView<?> parent,
					View view, int position, long id) {
				String clickedUsersId,clickedName;
				clickedEmail= nameValues.get(position);
				clickedName=nameEmailValues.get(position);
				System.out.println("Clicked Name: "+clickedEmail+"=> "+clickedName);
				st2 = new StringTokenizer(clickedName, "(");
				String tok[]=new String[3];
				int p=0;
				while (st2.hasMoreTokens()) {
					tok[p++]=st2.nextToken();
				}
				clickedEmail=tok[1];
				//find out Id of clicked email
				clickedUsersId=addFriendActivityFunction.fetchId(clickedEmail);
				System.out.println(clickedUsersId+" this is clicked user's name id:");
				//clickedUsersId= clickedUsersId.replaceAll("\\s+", "");
				userId="";
				try
				{
					receivedData = "";
					JSONArray jArray = new JSONArray(clickedUsersId);
					for(int i=0;i<jArray.length();i++)
					{
						JSONObject json_data = jArray.getJSONObject(i);
						userId=json_data.getInt(Constants.COLUMN_USER_ID)+"";
						user=json_data.getString(Constants.COLUMN_USER_NAME)+"";
						//user.replaceAll("\n", "");
						System.out.println(user+" :userId");
						receivedData += "\n" + json_data.getInt(Constants.COLUMN_USER_ID)+" ->"+json_data.getString(Constants.COLUMN_USER_NAME);
					}
				}
				catch(JSONException e)
				{
					Log.e("log_tag", "Error parsing data "+e.toString());
				}
				
				//find if they are friends already
				String friendCheck;
				friendCheck=addFriendActivityFunction.checkIfFriends(I.toString(), userId);
				friendCheck= friendCheck.replaceAll("\\s+", "");
				if ((Integer.parseInt(friendCheck))==0)
				{
					friends=false;
				}
				else //means they are friends already
				{
					friends=true;
				}
				if((Integer.parseInt(friendCheck))==0)  //if friendCheck==null
				{
					String seeIfFriends;
					// check other way around
					seeIfFriends=addFriendActivityFunction.checkIfFriends(userId,I.toString());
					seeIfFriends= seeIfFriends.replaceAll("\\s+", "");
					System.out.println("seeIfFriends"+seeIfFriends); 
					if (seeIfFriends.equals("0"))//not friends
					{
						alreadyFriends=1;
						System.out.println("alreadyFriends set"+friends);
					}
					else //(!(seeIfFriends.equals("0")))//means they are friends already
					{
						friends=true;
					}//if(!(seeIfFriends.equals("0"))) 
					
				}//if((Integer.parseInt(friendCheck))==0)
					
				
				//check if notification sent already
				
				String checkNotification=addFriendActivityFunction.checkNotification(myId, userId);
				checkNotification= checkNotification.replaceAll("\\s+", "");
				if ((Integer.parseInt(checkNotification))==0)
				{
					notification=false;
				}
				else//means notifications sent already
				{
					notification=true;
				}//if((Integer.parseInt(friendCheck))==1) closed
				if((Integer.parseInt(checkNotification))==0)  //if friendCheck==null
				{
					// check other way around, result contains if the other wat around notification has been sent
					String result;
					result=addFriendActivityFunction.checkNotification(userId, myId);
					result= result.replaceAll("\\s+", "");
					notificationResult=(Integer.parseInt(result));
					if (notificationResult==0)
					{
						System.out.println("notification already sent");
					}
					else//if(notificationResult==1)//means notifications sent already
					{
						notification=true;
					}    				
				}
				AlertDialog alert= new AlertDialog.Builder(AddFriendActivity.this).create();
				alert.setTitle("ADD FRIEND");
				if(radioClicked.getText().equals("Email"))
				alert.setMessage("Add "+user+" as friend");
				else
					alert.setMessage("Add "+clickedEmail+" as friend");
				alert.setButton("Cancel", new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						// TODO Auto-generated method stub
					}
				});
				alert.setButton2("Add Friend", new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						//  adding friend logic
						addingYourself=0;alreadyFriends=0;
						if(clickedEmail.equals(myEmailAdd))
						{
							//you are trying to add yourself
							addingYourself=1;
							System.out.println("Adding yourself");
							AlertDialog alert1= new AlertDialog.Builder(AddFriendActivity.this).create();
							alert1.setTitle("");
							alert1.setMessage("Trying to add yourself as friend");
							alert1.setButton("Cancel", new DialogInterface.OnClickListener() {
								@Override
								public void onClick(DialogInterface dialog, int which) {
									// TODO Auto-generated method stub
								}
							});
							alert1.show();
						}
						if(clickedEmail.equals(myName))
						{
							//you are trying to add yourself
							addingYourself=1;
							System.out.println("Adding yourself");
							AlertDialog alert1= new AlertDialog.Builder(AddFriendActivity.this).create();
							alert1.setTitle("");
							alert1.setMessage("Trying to add yourself as friend");
							alert1.setButton("Cancel", new DialogInterface.OnClickListener() {
								@Override
								public void onClick(DialogInterface dialog, int which) {
									// TODO Auto-generated method stub
								}
							});
							alert1.show();
						}
						if(friends==true&&addingYourself==0)
						{
							//they are friends already
							System.out.println("Friends Already");
							alreadyFriends=1;
							AlertDialog alert2= new AlertDialog.Builder(AddFriendActivity.this).create();
							alert2.setTitle("Already Friends");
							alert2.setMessage(myName+" and "+user+" are friends already");
							alert2.setButton("OK", new DialogInterface.OnClickListener() {
								@Override
								public void onClick(DialogInterface dialog, int which) {
									// TODO Auto-generated method stub
								}
							});
							alert2.show();
						}
						if(notification==true&&alreadyFriends==0&&addingYourself==0)
						{
							//notification already there
							System.out.println("Notification in there");
							AlertDialog alert3= new AlertDialog.Builder(AddFriendActivity.this).create();
							alert3.setTitle("Notification");
							alert3.setMessage("Request is already sent");
							alert3.setButton("OK", new DialogInterface.OnClickListener() {
								@Override
								public void onClick(DialogInterface dialog, int which) {
									// TODO Auto-generated method stub
								}
							});
							alert3.show();
						}
						if(notification==false&&alreadyFriends==0&&addingYourself==0)
						{
							//insert in notification relation
							String insertResult;
							insertResult=addFriendActivityFunction.addNotification(myId, userId);
							insertResult= insertResult.replaceAll("\\s+", "");
							System.out.println(insertResult+" insertResult");
							if(insertResult.equals("1"))
							{
								System.out.println("Friend Request Sent ");
								AlertDialog alert4= new AlertDialog.Builder(AddFriendActivity.this).create();
								alert4.setTitle("Friend Request");
								alert4.setMessage("Friend Request sent");
								alert4.setButton("OK", new DialogInterface.OnClickListener() {
									@Override
									public void onClick(DialogInterface dialog, int which) {
										// TODO Auto-generated method stub
									}
								});
								alert4.show();
							}
							
						}
					}
				});
				alert.show();
			}
		});
	}
 /*
  * This function handles search by email
  */
	private void emailFunction() {
	System.out.println("Email()");
    	adapter=new ArrayAdapter<String>(this,
				android.R.layout.simple_list_item_1,
				emailValues);
		emailList = (ListView) findViewById(R.id.userList);
		emailList.setAdapter(adapter);
		emailList.setTextFilterEnabled(true);
		emailList.setOnItemClickListener(new OnItemClickListener(){
			
			@Override
			/*
			 * This method fetches the information about the clicked item in the listview 
			 * and asks if user wants to add as a friend 
			 * 
			 */
			public void onItemClick(AdapterView<?> parent,
					View view, int position, long id) {
				String clickedUsersId;
				clickedEmail= emailValues.get(position);
				System.out.println("Clicked Email: "+clickedEmail);
				//find out Id of clicked email
				clickedUsersId=addFriendActivityFunction.fetchId(clickedEmail);
				System.out.println(clickedUsersId+" this is clicked user's id:");
				//clickedUsersId= clickedUsersId.replaceAll("\\s+", "");
				userId="";
				try
				{
					receivedData = "";
					JSONArray jArray = new JSONArray(clickedUsersId);
					for(int i=0;i<jArray.length();i++)
					{
						JSONObject json_data = jArray.getJSONObject(i);
						userId=json_data.getInt(Constants.COLUMN_USER_ID)+"";
						user=json_data.getString(Constants.COLUMN_USER_NAME)+"";
						//user.replaceAll("\n", "");
						System.out.println(user+" :userId");
						receivedData += "\n" + json_data.getInt(Constants.COLUMN_USER_ID)+" ->"+json_data.getString(Constants.COLUMN_USER_NAME);
					}
				}
				catch(JSONException e)
				{
					Log.e("log_tag", "Error parsing data "+e.toString());
				}
				
				//find if they are friends already
				String friendCheck;
				friendCheck=addFriendActivityFunction.checkIfFriends(I.toString(), userId);
				friendCheck= friendCheck.replaceAll("\\s+", "");
				if ((Integer.parseInt(friendCheck))==0)
				{
					friends=false;
				}
				else //means they are friends already
				{
					friends=true;
				}
				if((Integer.parseInt(friendCheck))==0)  //if friendCheck==null
				{
					String seeIfFriends;
					// check other way around
					seeIfFriends=addFriendActivityFunction.checkIfFriends(userId,I.toString());
					seeIfFriends= seeIfFriends.replaceAll("\\s+", "");
					System.out.println("seeIfFriends"+seeIfFriends); 
					if (seeIfFriends.equals("0"))//not friends
					{
						alreadyFriends=1;
						System.out.println("alreadyFriends set"+friends);
					}
					else //(!(seeIfFriends.equals("0")))//means they are friends already
					{
						friends=true;
					}//if(!(seeIfFriends.equals("0"))) 
					
				}//if((Integer.parseInt(friendCheck))==0)
					
				
				//check if notification sent already
				
				String checkNotification=addFriendActivityFunction.checkNotification(myId, userId);
				checkNotification= checkNotification.replaceAll("\\s+", "");
				if ((Integer.parseInt(checkNotification))==0)
				{
					notification=false;
				}
				else//means notifications sent already
				{
					notification=true;
				}//if((Integer.parseInt(friendCheck))==1) closed
				if((Integer.parseInt(checkNotification))==0)  //if friendCheck==null
				{
					// check other way around, result contains if the other wat around notification has been sent
					String result;
					result=addFriendActivityFunction.checkNotification(userId, myId);
					result= result.replaceAll("\\s+", "");
					notificationResult=(Integer.parseInt(result));
					if (notificationResult==0)
					{
						System.out.println("notification already sent");
					}
					else//if(notificationResult==1)//means notifications sent already
					{
						notification=true;
					}    				
					
				}
				AlertDialog alert= new AlertDialog.Builder(AddFriendActivity.this).create();
				alert.setTitle("ADD FRIEND");
				if(radioClicked.getText().equals("Email"))
				alert.setMessage("Add "+user+" as friend");
				else
					alert.setMessage("Add "+clickedEmail+" as friend");
				alert.setButton("Cancel", new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						// TODO Auto-generated method stub
					}
				});
				alert.setButton2("Add Friend", new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						//  adding friend logic
						addingYourself=0;alreadyFriends=0;
						if(clickedEmail.equals(myEmailAdd))
						{
							//you are trying to add yourself
							addingYourself=1;
							System.out.println("Adding yourself");
							AlertDialog alert1= new AlertDialog.Builder(AddFriendActivity.this).create();
							alert1.setTitle("");
							alert1.setMessage("Trying to add yourself as friend");
							alert1.setButton("Cancel", new DialogInterface.OnClickListener() {
								@Override
								public void onClick(DialogInterface dialog, int which) {
									// TODO Auto-generated method stub
								}
							});
							alert1.show();
						}
						if(clickedEmail.equals(myName))
						{
							//you are trying to add yourself
							addingYourself=1;
							System.out.println("Adding yourself");
							AlertDialog alert1= new AlertDialog.Builder(AddFriendActivity.this).create();
							alert1.setTitle("");
							alert1.setMessage("Trying to add yourself as friend");
							alert1.setButton("Cancel", new DialogInterface.OnClickListener() {
								@Override
								public void onClick(DialogInterface dialog, int which) {
									// TODO Auto-generated method stub
								}
							});
							alert1.show();
						}
					
						if(friends==true&&addingYourself==0)
						{
							//they are friends already
							System.out.println("Friends Already");
							alreadyFriends=1;
							AlertDialog alert2= new AlertDialog.Builder(AddFriendActivity.this).create();
							alert2.setTitle("Already Friends");
							alert2.setMessage(myName+" and "+user+" are friends already");
							alert2.setButton("OK", new DialogInterface.OnClickListener() {
								@Override
								public void onClick(DialogInterface dialog, int which) {
									// TODO Auto-generated method stub
								}
							});
							alert2.show();
						}
						if(notification==true&&alreadyFriends==0&&addingYourself==0)
						{
							//notification already there
							System.out.println("Notification in there");
							AlertDialog alert3= new AlertDialog.Builder(AddFriendActivity.this).create();
							alert3.setTitle("Notification");
							alert3.setMessage("Request is already sent");
							alert3.setButton("OK", new DialogInterface.OnClickListener() {
								@Override
								public void onClick(DialogInterface dialog, int which) {
									// TODO Auto-generated method stub
								}
							});
							alert3.show();
						}
						if(notification==false&&alreadyFriends==0&&addingYourself==0)
						{
							//insert in notification relation
							String insertResult;
							insertResult=addFriendActivityFunction.addNotification(myId, userId);
							insertResult= insertResult.replaceAll("\\s+", "");
							System.out.println(insertResult+" insertResult");
							if(insertResult.equals("1"))
							{
								System.out.println("Friend Request Sent ");
								AlertDialog alert4= new AlertDialog.Builder(AddFriendActivity.this).create();
								alert4.setTitle("Friend Request");
								alert4.setMessage("Friend Request sent");
								alert4.setButton("OK", new DialogInterface.OnClickListener() {
									@Override
									public void onClick(DialogInterface dialog, int which) {
										// TODO Auto-generated method stub
									}
								});
								alert4.show();
							}
							
						}
					}
				});
				alert.show();
			}
		});
	}
	/*
     * This onbackPressed() is overridden and it takes the navigation to the Home Page
     * 
     * 
     */
	@Override
	public void onBackPressed()
	{
		Intent back=new Intent(AddFriendActivity.this,HomeActivity.class);
		startActivity(back);
		finish();
	}
}//main class ends
